package xyz.xtt.schedule.config.datasource;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;

@Configuration
@MapperScan(basePackages = "xyz.xtt.schedule.mapper.blockchain", sqlSessionFactoryRef = "sqlSessionFactoryBlockchain", sqlSessionTemplateRef = "sqlSessionTemplateBlockchain")
public class DatasourceConfigBlockChain {
	// 将这个对象放入Spring容器中
	@Bean(name = "dataSourceBlockchain")
	// 表示这个数据源是默认数据源
	// 读取application.properties中的配置参数映射成为一个对象
	// prefix表示参数的前缀
	@ConfigurationProperties(prefix = "spring.datasource.blockchain")
	public DataSource getDateSource1() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "sqlSessionFactoryBlockchain")
	// 表示这个数据源是默认数据源
	@Primary
	// @Qualifier表示查找Spring容器中名字为test1DataSource的对象
	public SqlSessionFactory test1SqlSessionFactory(@Qualifier("dataSourceBlockchain") DataSource datasource) throws Exception {
		MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
		bean.setDataSource(datasource);
		bean.setMapperLocations(
				// 设置mybatis的xml所在位置
				new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/blockchain/*.xml"));
		return bean.getObject();
	}

	@Bean("sqlSessionTemplateBlockchain")
	// 表示这个数据源是默认数据源
	public SqlSessionTemplate test1sqlsessiontemplate(@Qualifier("sqlSessionFactoryBlockchain") SqlSessionFactory sessionfactory) {
		return new SqlSessionTemplate(sessionfactory);
	}
}